package com.scut.chenlujie.library.clink.sample.foo.handle;

import com.scut.chenlujie.library.clink.box.StringReceivePacket;
import com.scut.chenlujie.library.clink.core.Connector;
import com.scut.chenlujie.library.clink.core.IoContext;
import com.scut.chenlujie.library.clink.core.Packet;
import com.scut.chenlujie.library.clink.core.ReceivePacket;
import com.scut.chenlujie.library.clink.sample.foo.foo;
import com.scut.chenlujie.library.clink.utils.CloseUtils;
import java.io.*;
import java.nio.channels.SocketChannel;



public class ConnectorHandler extends Connector{
    private final File cachePath;
    private final String clientInfo;
    private final ConnectorCloseChain closeChain = new DefaultPrintConnectorCloseChain();
    private final ConnectorStringPacketChain stringPacketChain = new DefaultNonConnectorStringPacketChain();

    public ConnectorHandler(SocketChannel socketChannel, File cachePath ) throws IOException {
        this.cachePath = cachePath;
        this.clientInfo = socketChannel.getRemoteAddress().toString();
        setup(socketChannel);

    }

    public String getInfo(){
        return clientInfo;
    }

    @Override
    public void onChannelClosed(SocketChannel channel) {
        super.onChannelClosed(channel);
        closeChain.handle(this,this);
    }

    @Override
    protected File createNewReceivedFile() {
        return foo.createRandomTemp(cachePath);
    }

    @Override
    protected void onReceivePacket(ReceivePacket packet) {
        super.onReceivePacket(packet);
        switch (packet.type()){
            case Packet.TYPE_MEMORY_STRING:{
                deliveryStringPacket((StringReceivePacket) packet);
                System.out.println("receive");
            }
            default:{
                System.out.println("New Packet :" + packet.type() +" - " + packet.length());
            }
        }

}

    private void deliveryStringPacket(StringReceivePacket packet) {
        IoContext.get().getScheduler().delivery(()-> stringPacketChain.handle(this,packet));

    }

    public void exit() {
        CloseUtils.close(this);

    }

    private void exitBySelf() {
        exit();
        //clientHandlerCallback.onSelfClosed(this);
    }

//    //回调的精妙设计
//    public interface ClientHandlerCallback {
//        //自身关闭
//        void onSelfClosed(ClientHandler handler);
//
//        //收到消息通知回去
//        void onNewMessageArrived(ClientHandler handler, String msg);
//    }

    public ConnectorStringPacketChain getStringPacketChain(){
        return stringPacketChain;
    }

    public ConnectorCloseChain getCloseChain(){
        return closeChain;
    }

}
